// pages/snapUpDetail/snapUpDetail.js
var http = require('../../utils/http.js');
var util = require('../../utils/util.js');
var config = require('../../utils/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hideModal: true,
    prodCommData: {},
    littleCommPage: [],
    evaluate: -1,
    isCollection: false,
    prodCommPage: {
      current: 0,
      pages: 0,
      records: []
    },
    imgs: '', //商品图片
    /** swiper */
    indicatorDots: true,
    autoplay: true,
    indicatorColor: '#f2f2f2',
    interval: 3000,
    duration: 1000,
    indicatorActiveColor: '#e43130',
    /** swiper */
    content: '', //商品详情介绍
    skuShow: false,  //sku选择
    popupShow: false,
    commentShow: false,
    defaultSku: undefined,
    skuGroup: {},
    allProperties: [],
    prodNum: 1, //数量+-
    skuId: 0,
    prodId: 0,

    totalCartNum: 0,
    pic: "",
    imgs: '',
    prodName: '',
    price: 0,
    content: '',
    brief: '',
    picDomain: config.picDomain,
    groupSkuId:'',
    groupTeamId: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      prodId: options.prodid,
    });

    if (options.scene) {
      // console.log(options.scene)
      const scene = decodeURIComponent(options.scene);
      var params = scene.split(",");
      this.setData({
        prodId: params[0],
      });
    }

    // 加载商品信息
    this.getProdInfo();
    // 加载评论项
    this.getLittleProdComm();
  },


  /**
   * 获取商品信息
   */
  getProdInfo() {
    wx.showLoading();
    var params = {
      url: "/prod/prodInfo",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        // userType: 0
      },
      callBack: (res) => {
        // console.log(res);
        var imgStrs = res.imgs;
        var imgs = imgStrs.split(",");
        var content = util.formatHtml(res.content);
        this.setData({
          imgs: imgs,
          content: content,
          price: res.price,
          prodName: res.prodName,
          prodId: res.prodId,
          brief: res.brief,
          // skuId: res.skuId
          skuList: res.skuList,
          pic: res.pic
        });
        // 获取优惠券
        this.getCouponList();
        // 组装sku
        this.groupSkuProp();

        wx.hideLoading();
      }
    };
    http.request(params);
  },

  showSku: function () {
    this.setData({
      skuShow: true
    });
  },


  /**
   * 根据sku的属性 分组
   */
  groupSkuProp: function () {
    var skuList = this.data.skuList;
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      return;
    }
    var skuGroup = {};
    var allProperties = [];
    var propKeys = [];
    for (var i = 0; i < skuList.length; i++) {
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }
      var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
  },

  /**
   * 将已选的 {key:val,key2:val2}转换成 [val,val2]
   */
  parseSelectedObjToVals: function () {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    // console.log(selectedProperties);
    this.setData({
      selectedProp: selectedProp
    });

    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectedProperties) {
        this.setData({
          defaultSku: this.data.skuList[i]
        });
        break;
      }
    }
  },

  /**
   * 点击选择规格
   */
  toChooseItem: function (e) {
    var ok = e.currentTarget.dataset.ok;
    if (!ok) {
      return;
    }
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  /**
  * 加数量
  */
  onCountPlus: function () {
    var prodNum = this.data.prodNum;
    if (prodNum < 1000) {
      this.setData({
        prodNum: prodNum + 1
      });
    }
  },

  /**
  * 减数量
  */
  onCountMinus: function () {
    var prodNum = this.data.prodNum;
    if (prodNum > 1) {
      this.setData({
        prodNum: prodNum - 1
      });
    }
  },

  /**
   * 关闭弹窗
   */
  closePopup: function () {
    this.setData({
      popupShow: false,
      skuShow: false,
      commentShow: false
    });
  },


  /**
   * 获取部分评论
   */
  getLittleProdComm() {
    if (this.data.prodCommPage.records.length) {
      return;
    }
    this.getProdCommPage();
  },
  getMoreCommPage(e) {
    this.getProdCommPage();
  },
  // 获取分页获取评论
  getProdCommPage(e) {
    if (e) {
      if (e.currentTarget.dataset.evaluate === this.data.evaluate) {
        return;
      }
      this.setData({
        prodCommPage: {
          current: 0,
          pages: 0,
          records: []
        },
        evaluate: e.currentTarget.dataset.evaluate
      })
    }
    http.request({
      url: "/p/prodComm/prodCommPageByProd",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        size: 10,
        current: this.data.prodCommPage.current + 1,
        evaluate: this.data.evaluate
      },
      callBack: (res) => {
        res.records.forEach(item => {
          if (item.pics) {
            item.pics = item.pics.split(',')
          }
        })
        let records = this.data.prodCommPage.records
        records = records.concat(res.records)
        this.setData({
          prodCommPage: {
            current: res.current,
            pages: res.pages,
            records: records
          }
        })
        // 如果商品详情中没有评论的数据，截取两条到商品详情页商品详情
        if (!this.data.littleCommPage.length) {
          this.setData({
            littleCommPage: records.slice(0, 2)
          })
        }
      }
    })
  },
  showComment: function () {
    this.setData({
      commentShow: true
    });
  },


  /**
   * 立即购买
   */
  buyNow: function() {
    wx.setStorageSync("orderItem", JSON.stringify({
      prodId: this.data.prodId,
      skuId: this.data.defaultSku.skuId,
      prodCount: this.data.prodNum,
      shopId: this.data.shopId,
      distributionCardNo: this.data.distributionCardNo
    }));
    wx.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=1',
    })

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 显示遮罩层
   */
  showModal: function () {
    var that = this;
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 600,//动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快 
      timingFunction: 'ease',//动画的效果 默认值是linear 
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn();//调用显示动画
    }, 100)
  },


  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,//动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快 
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画
    setTimeout(function () {
      that.setData({ hideModal: true })
    }, 720)//先执行下滑动画，再隐藏模块
  },


  /**
   * 动画集
   */
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  /**
   * 跳转到首页
   */
  toHomePage: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 跳转到购物车
   */
  toCartPage: function () {
    wx.switchTab({
      url: '/pages/basket/basket',
    })
  },
  /**
   * 查看拼团团队
   */
  toGroupTempInfoPage: function (e) {
    wx.navigateTo({
      url: '/pages/spellMembersDetails/spellMembersDetails?groupTeamId=' + e.currentTarget.dataset.groupTeamId,
    })
  },
  /**
   * 拼团确认订单
   */
  groupConfirmOrder: function(e){
    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(()=>{
      wx.hideLoading();
      wx.setStorageSync("groupOrderItem", JSON.stringify({
        groupSkuId: 1,// this.data.groupSkuId,
        prodCount:  this.data.prodNum,
        groupTeamId: 0 // this.data.groupTeamId
      }));
      wx.navigateTo({
        url: '/pages/groupConfirmOrder/groupConfirmOrder',
      })
    })
  }

})